package com.lxmes.sales.service.impl;

import java.util.List;

import com.lxmes.base.domain.JcWarehouseinfoKuwei;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.bean.BeanUtils;
import com.lxmes.sales.domain.AssetKucun;
import com.lxmes.sales.mapper.AssetKucunMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.lxmes.sales.mapper.AssetRukuMapper;
import com.lxmes.sales.domain.AssetRuku;
import com.lxmes.sales.service.IAssetRukuService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资产入库Service业务层处理
 *
 * @author cdc
 * @date 2024-08-14
 */
@Service
public class AssetRukuServiceImpl implements IAssetRukuService
{
    @Autowired
    private AssetRukuMapper assetRukuMapper;
    @Autowired
    private AssetKucunMapper assetKucunMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询资产入库
     *
     * @param id 资产入库主键
     * @return 资产入库
     */
    @Override
    public AssetRuku selectAssetRukuById(Long id)
    {
        return assetRukuMapper.selectAssetRukuById(id);
    }

    /**
     * 查询资产入库列表
     *
     * @param assetRuku 资产入库
     * @return 资产入库
     */
    @Override
    public List<AssetRuku> selectAssetRukuList(AssetRuku assetRuku)
    {
        return assetRukuMapper.selectAssetRukuList(assetRuku);
    }

    /**
     * 新增资产入库
     *
     * @param assetRuku 资产入库
     * @return 结果
     */
    @Override
    public int insertAssetRuku(AssetRuku assetRuku)
    {
        List<AssetRuku> list = assetRuku.getInfoList();
        if(list.size()>0){
            for ( AssetRuku info:list) {
                info.setId(null);
                info.setOrgCode(SecurityUtils.getFactoryCode());
                info.setOrgName(SecurityUtils.getFactoryName());
                info.setRukuType(assetRuku.getRukuType());
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                String number= info.getAssetCode()+ NewNumber.createNewNumber(assetRukuMapper.getNewBarcode(DateUtils.getDate(),info.getAssetCode()));
                info.setBarcode(number);
                assetRukuMapper.insertAssetRuku(info);
            }
        }else {
            throw new ServiceException("资产入库明细不存在！");
        }
        return 1;
    }

    /**
     * 修改资产入库
     *
     * @param assetRuku 资产入库
     * @return 结果
     */
    @Override
    public int updateAssetRuku(AssetRuku assetRuku)
    {
        return assetRukuMapper.updateAssetRuku(assetRuku);
    }

    @Override
    @Transactional
    public int shAssetRuku(AssetRuku assetRuku) {
        List<Long> idsList = assetRuku.getIds();
        for (Long id:idsList) {
            AssetRuku rk = assetRukuMapper.selectAssetRukuById(id);
            if(rk.getShStatus().equals("1")){
                throw new ServiceException("资产入库单【"+rk.getAssetCode()+"】已审核，不能重复审核！");
            }
            rk.setShStatus("1");
            rk.setShName(SecurityUtils.getUsername());
            rk.setShDate(DateUtils.getNowDate());
            assetRukuMapper.updateAssetRuku(rk);
            this.syncStock(rk);
        }
        return 1;
    }

    @Override
    @Transactional
    public int qxshAssetRuku(AssetRuku assetRuku) {
        List<Long> idsList = assetRuku.getIds();
        for (Long id:idsList) {
            AssetRuku rk = assetRukuMapper.selectAssetRukuById(id);
            if(rk.getShStatus().equals("0")){
                throw new ServiceException("资产入库单【"+rk.getAssetCode()+"】未审核，不能取消审核！");
            }
            rk.setShStatus("0");
            rk.setShName("");
            rk.setShDate(DateUtils.getNowDate());
            assetRukuMapper.updateAssetRuku(rk);
            this.qxSyncStock(rk);
        }
        return 1;
    }

    //同步库存
    public void  syncStock(AssetRuku assetRuku){
        AssetKucun queryKucun = new AssetKucun();
        queryKucun.setOrgCode(SecurityUtils.getFactoryCode());
        queryKucun.setBarcode(assetRuku.getBarcode());
        AssetKucun kucun = assetKucunMapper.selectAssetKucunByObj(queryKucun);
        if(kucun==null){
            kucun = new AssetKucun();
            BeanUtils.copyProperties(assetRuku,kucun);
            kucun.setId(null);
            kucun.setOrgCode(SecurityUtils.getFactoryCode());
            kucun.setOrgName(SecurityUtils.getFactoryName());
            kucun.setCreateBy(SecurityUtils.getUsername());
            kucun.setCreateTime(DateUtils.getNowDate());
            kucun.setKcNum(assetRuku.getRukuNum());
            kucun.setAmount(kucun.getKcNum().multiply(kucun.getUnitPrice()));
            assetKucunMapper.insertAssetKucun(kucun);
        }else {
            kucun.setKcNum(kucun.getKcNum().add(assetRuku.getRukuNum()));
            kucun.setAmount(kucun.getKcNum().multiply(kucun.getUnitPrice()));
            assetKucunMapper.updateAssetKucun(kucun);
        }
    }
    //同步库存
    public void  qxSyncStock(AssetRuku assetRuku){
        AssetKucun queryKucun = new AssetKucun();
        queryKucun.setOrgCode(SecurityUtils.getFactoryCode());
        queryKucun.setBarcode(assetRuku.getBarcode());
        AssetKucun kucun = assetKucunMapper.selectAssetKucunByObj(queryKucun);
        if(kucun!=null){
            if(kucun.getKcNum().compareTo(assetRuku.getRukuNum())<0){
                throw new ServiceException("资产代码【"+assetRuku.getAssetCode()+"】库存不足，不能取消审核！");
            }
            kucun.setKcNum(kucun.getKcNum().subtract(assetRuku.getRukuNum()));
            kucun.setAmount(kucun.getKcNum().multiply(kucun.getUnitPrice()));
            assetKucunMapper.updateAssetKucun(kucun);
        }
    }
    /**
     * 批量删除资产入库
     *
     * @param ids 需要删除的资产入库主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAssetRukuByIds(Long[] ids)
    {
        for (int i = 0; i <ids.length ; i++) {
            AssetRuku assetRuku = assetRukuMapper.selectAssetRukuById(ids[i]);
            if(assetRuku.getShStatus().equals("1")){
                throw new ServiceException("资产入库单【"+assetRuku.getAssetCode()+"】已审核，先取消审核再删除！");
            }
        }
        return assetRukuMapper.deleteAssetRukuByIds(ids);
    }

    /**
     * 删除资产入库信息
     *
     * @param id 资产入库主键
     * @return 结果
     */
    @Override
    public int deleteAssetRukuById(Long id)
    {
        return assetRukuMapper.deleteAssetRukuById(id);
    }
    @Override
    public String imporIteminfo(List<AssetRuku> assetRukuList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(assetRukuList) || assetRukuList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AssetRuku assetRuku : assetRukuList)
        {
            try
            {
                BeanValidators.validateWithException(validator, assetRuku);
                assetRuku.setCreateBy(operName);
                assetRuku.setUpdateBy(operName);
                this.insertAssetRuku(assetRuku);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
